package com.zjw.service.impl;

import com.zjw.constants.SystemConstants;
import com.zjw.annotation.domain.ResponseResult;
import com.zjw.annotation.domain.entity.User;
import com.zjw.annotation.domain.vo.AdminLoginVo;
import com.zjw.enums.AppHttpCodeEnum;
import com.zjw.service.AdminLoginService;
import com.zjw.utils.JwtUtil;
import com.zjw.utils.RedisCache;
import com.zjw.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Service
public class AdminLoginServiceImpl implements AdminLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
//        创建Authentication的实现类对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

//        使用AuthenticationManager实现类的.authenticate方法
//        他会自动调用ioc容器中的UserDetailsService中的loadUserByName
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

//        在authenticate方法中会对输入的用户名密码和数据库中查询返回的LoginUser进行匹配，如果不匹配返回Null
        if (authenticate == null) {
//            用户名或密码不正确
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }

//        如果正确，生成jwt
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        Long id = principal.getUser().getId();

//        更具id生成jwt 1.返回给前端， 2.处理为key存入Redis
        String jwt = JwtUtil.createJWT(id.toString());

//      2. 存入Redis,  JWT_ADMIN_KEY_PREFIX+jwt: User

        redisCache.setCacheObject(SystemConstants.JWT_ADMIN_KEY_PREFIX + principal.getUser().getId().toString(),
                principal.getUser());

        return ResponseResult.okResult(new AdminLoginVo(jwt));
    }

    @Override
    public ResponseResult logout() {
//        获取当前用户id
        Long id = SecurityUtil.getCurUserId();

//        从Redis中移除
        redisCache.deleteObject(SystemConstants.JWT_ADMIN_KEY_PREFIX + id);

//        返回响应
        return ResponseResult.okResult();
    }


}
